<template>
  <view class="test-vision">
    <view class="header">{{ testTitle2 }}视力测试</view>
    <view class="message-box">
      <view class="left">
        <view class="left-one">
          <view class="name">
            {{ $store.state.name || "" }}
          </view>
          <view class="sex">
            {{ $store.state.sex || "" }}
          </view>
          <view class="class">
            {{ parseClassInfo($store.state.nativeData.class_info || "") }}
          </view>
        </view>
        <view class="school">
          {{ $store.state.school || "" }}
        </view>
      </view>
      <view class="right">
        <view class="item">
          {{ testTitle2 }}
          视力检测({{ testTitle }})
        </view>
        <view class="item"> 请在{{ distance }}米距离测试 </view>
      </view>
    </view>
    <view class="test-box">
      <SeekBar
        key="1"
        :active="active"
        :list="list1"
        style="margin-left: 20px; float: left"
      />
      <SeekBar
        key="2"
        :active="active"
        :lineLeft="true"
        :list="list2"
        style="margin-right: 20px; float: right"
      />
      <view class="test-show">
        <view class="test-show-context">
          <image
            src="@/static/E.png"
            :style="{
              width: getContextSize,
              height: getContextSize,
              maxWidth: '50vw',
              maxHeight: '50vw',
              transition: '0.1s',
              transform: getContextTransform,
            }"
          ></image>
        </view>
      </view>
      <view class="show-message">{{ list1[active] }}</view>
    </view>
    <view class="edit-box">
      <button class="t" @click="buttonClick(3)">上</button>
      <button class="r" @click="buttonClick(0)">右</button>
      <button class="b" @click="buttonClick(1)">下</button>
      <button class="l" @click="buttonClick(2)">左</button>
      <button class="not-button" @click="buttonClick(-1)">
        <view class="center"> 不知道 </view>
      </button>
    </view>

    <Toast ref="toastRef" />
    <Choice ref="choiceRef" />
  </view>
</template>


<script>
import { showToast, choice } from "@/common/index/utils/toast.js"
import SeekBar from "@/components/index/SeekBar.vue"
import { newVisionCompany, oldVisionCompany, testSizes, testCounts } from "@/common/index/config/constData"
import { clientEvent } from '@/common/index/utils/ClientEvent.js'
import { KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_BOTTOM, KEY_ENTER, KEY_BACK } from '@/common/index/config/Event'
import { exitPage, indexToVisionComany, toLogin } from "@/common/index/utils/common"
import { lastTestVsiionResult } from "@/common/index/config/data"
import Toast from '@/components/index/Toast.vue'
import Choice from '@/components/index/Choice.vue'
import {
  toastRef, choiceRef
} from "@/common/index/utils/toast.js"
/**
 * 测试视力页面
 */
export default {
  data () {
    return {
      list1: oldVisionCompany,
      list2: newVisionCompany,
      testTitle: "左眼视力",
      active: 5,
      answer: 0,
      answerSize: 1,
      result: [],
      eventList: [],
      lastTestResult: [],
      testTitle2: "",
      distance: 5,
      initTestCompanyIndex: 0,
      testLeft: [0.1, 2],
      testRight: [0.1, 2],
      /**
       * 0测左眼
       * 1测右眼
       */
      testStep: 0,
      uuid: undefined,
      lockDistance: false,
      isAddDistance: true
    }
  },
  /**
   * 
   * @param {*} param0 testTitle:测试标题 ，distance：测试米数，initTestCompanyIndex：开始测试单位下标 
   */
  onLoad ({ testTitle, distance, initTestCompanyIndex, uuid, lockDistance }) {
    this.testTitle2 = testTitle
    this.distance = +distance
    this.initTestCompanyIndex = +initTestCompanyIndex
    this.active = this.initTestCompanyIndex
    this.uuid = uuid
    this.lockDistance = lockDistance == "true" ? true : false
  },
  created () {
    this.bindEvent()
    this.answer = this.getRandom()
  },
  mounted () {
    toastRef.value = this.$refs.toastRef
    choiceRef.value = this.$refs.choiceRef
    choice(this.testTitle2 + "视力检测", [`在${this.distance}米距离测试`, "先测试左眼视力", "你准备好了吗?"], false, undefined, undefined, "准备好了")
  },
  components: {
    SeekBar,
    Toast,
    Choice
  },
  watch: {
    active (val) {
      let t = val / this.list1.length
      this.answerSize = 1 - t
    }
  },
  computed: {
    getContextTransform () {
      return `rotateZ(${this.answer * 90 + 90}deg)`
    },
    getContextSize () {
      return `${testSizes[this.active]}mm`
    },
    parseClassInfo () {

      return (info) => {
        let str = ""
        if (info.indexOf("班") != -1) {
          str = info.split("班")[0] + "班"
        } else {
          str = info
        }
        if (str.length >= 9) {
          str = str.substring(0, 7)
        }
        return str
      }
    }
  },

  methods: {
    backpress () {
      choice("返回登录", "你要退出测试吗？", true, () => toLogin())
    },
    buttonClick (index) {
      if (index == this.answer) {
        // 判断是否调整距离
        if (this.active >= 11 && this.testStep == 0 && this.distance < 5 && (!this.lockDistance) && this.isAddDistance) {//看不见0.1时，减少测量米数
          choice(`调整距离`, `需要调整距离为${this.distance + 1}米吗?`, true, () => {
            this.result = []
            this.distance += 1
            this.active -= 2
          }, () => {
            this.isAddDistance = false

            this.result.push(true)
            this.execLogic()
          })
          return
        } else {
          this.result.push(true)
        }
      } else {
        // 判断是否调整距离
        if (this.active == 0 && this.testStep == 0 && this.distance > 1 && (!this.lockDistance)) {//看不见0.1时，减少测量米数
          choice(`错误`, `需要调整距离为${this.distance - 1}米吗?`, true, () => {
            this.result = []
            this.distance -= 1
            this.isAddDistance = false
          }, () => {
            this.result.push(false)
            this.execLogic()
          })
          return
        } else {
          this.result.push(false)
        }
      }
      this.execLogic()
    },
    unLoad () {
      this.unmounted()
    },
    /**
     * 获取随机的E方向
     */
    getRandom () {
      let random = Math.floor(Math.random() * 4)
      if (random == this.answer) {
        return this.getRandom()
      }
      return random
    },
    /**
     * 执行检测逻辑
     */
    execLogic () {
      let flag = true
      for (let item of this.result) {
        if (!item) {
          flag = false
          break
        }
      }
      if (flag) {
        this.answer = this.getRandom()
        if (this.result.length >= testCounts[this.active]) {
          if (this.active + 1 == testCounts.length) {
            this.end()
          } else {
            this.result = []
            this.active++
          }
        }
      } else {
        this.end()
      }
    },
    end () {
      const func = (message, callback) => {
        const toast = showToast(this.testTitle + ":" + indexToVisionComany(this.active), "3秒后测试" + message, callback, 3000)
        let i = 3
        let timer = setInterval(() => {
          i--
          toast.content = `${i}秒后测试${message}`
          if (i == 0) {
            this.testTitle = "右眼视力"
            clearInterval(timer)
          }
        }, 1000)
      }

      switch (this.testStep) {
        case 0: {
          let callback = () => {
            this.result = []
            this.answer = this.getRandom()
            this.active = this.initTestCompanyIndex
            this.testStep++
          }
          this.testLeft[1] = Math.max(this.result.length - 1, 0)
          this.testLeft[0] = this.active
          func(this.testTitle2 + "右眼视力", callback)
        }; break
        case 1: {
          this.testRight[1] = Math.max(this.result.length - 1, 0)
          this.testRight[0] = this.active
          choice("测试完成", [
            this.testTitle2 + "左眼视力:" + indexToVisionComany(this.testLeft[0]) + " +" + this.testLeft[1],
            this.testTitle2 + "右眼视力:" + indexToVisionComany(this.testRight[0]) + " +" + this.testRight[1]
          ], false, () => this.commit())
        } break
      }
    },
    /**
     * 绑定按钮事件
     */
    bindEvent () {
      this.eventList = [
        () => this.buttonClick(3),
        () => this.buttonClick(0),
        () => this.buttonClick(1),
        () => this.buttonClick(2),
        () => choice("选择", "不知道？", true, () => this.buttonClick(-1))
      ]
      clientEvent.on(KEY_UP, this.eventList[0], this)
      clientEvent.on(KEY_RIGHT, this.eventList[1], this)
      clientEvent.on(KEY_BOTTOM, this.eventList[2], this)
      clientEvent.on(KEY_LEFT, this.eventList[3], this)
      clientEvent.on(KEY_ENTER, this.eventList[4], this)
      clientEvent.on(KEY_BACK, this.backpress, this)
    },
    /**
     * 卸载按钮绑定事件
     */
    unmounted () {
      clientEvent.off(KEY_UP, this.eventList[0], this)
      clientEvent.off(KEY_RIGHT, this.eventList[1], this)
      clientEvent.off(KEY_BOTTOM, this.eventList[2], this)
      clientEvent.off(KEY_LEFT, this.eventList[3], this)
      clientEvent.off(KEY_BACK, this.backpress, this)
      clientEvent.off(KEY_ENTER, this.eventList[4], this)
    },
    /**
     * 提交结果退出页面
     */
    commit () {
      this.unmounted()
      lastTestVsiionResult.distance = this.distance
      lastTestVsiionResult.leftCompanyIndex = this.testLeft[0]
      lastTestVsiionResult.rightCompanyIndex = this.testRight[0]
      lastTestVsiionResult.leftCorrectNumber = this.testLeft[1]
      lastTestVsiionResult.rightCorectNumber = this.testRight[1]
      if (this.uuid)
        lastTestVsiionResult.uuid = this.uuid
      exitPage()
    },
    onShow () {
      toastRef.value = this.$refs.toastRef
      choiceRef.value = this.$refs.choiceRef
    },
  },
  onShow () {
    this.bindEvent()
  },
  onHide () {
    this.unmounted()
  },
  onUnload () {
    this.unmounted()
  }
}
</script>

<style lang="scss" scoped>
.test-vision {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.vision-result {
  height: 40px;
  display: flex;
  justify-content: center;
  flex-shrink: 0;

  view {
    width: 2.4vw;
    height: 2.4vw;
    margin: 2vw 1vw;
  }
}

.vision-result-right {
  background-color: red;
}

.vision-result-wrong {
  background-color: black;
}

.test-box {
  margin-top: 40px;
  height: 53vh;
  position: relative;
  flex-shrink: 0;
  margin-bottom: 30px;

  .test-show {
    position: absolute;
    left: 50%;
    top: 50%;
    transition: 0.5s;
    transform: translate(-50%, -50%);
  }

  view {
    flex: 1;
  }
  .show-message {
    font-size: 8vw;
    position: absolute;
    top: -5%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.test-show-context {
  color: rgba(16, 16, 16, 1);
  text-align: center;
  transition: 0.1s;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.edit-box {
  border-top: 2px solid rgba(187, 187, 187, 1);
  flex: 1;
  position: relative;
  max-height: 60vw;

  button {
    cursor: pointer;
    position: absolute;
    width: 21.2vw;
    height: 8.2vw;
    border-radius: 1vw;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    font-size: 2.8vw;
    text-align: center;
    font-family: Microsoft Yahei;
    border: 1px solid rgba(187, 187, 187, 1);
  }

  .l {
    top: 50%;
    left: 10%;
    transform: translateY(-50%);
  }

  .r {
    top: 50%;
    right: 10%;
    transform: translateY(-50%);
  }

  .t {
    top: 8%;
    left: 50%;
    transform: translateX(-50%);
  }

  .b {
    bottom: 8%;
    left: 50%;
    transform: translateX(-50%);
  }

  .not-button {
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 16vw;
    height: 11vw;
    line-height: 9vw;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    font-size: 2vw;
    text-align: center;
    font-family: Arial;
    border: 1px solid rgba(187, 187, 187, 1);

    .center {
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
}

.message-box {
  height: 10vw;
  width: 100vw;
  font-family: "Microsoft YaHei";
  font-style: normal;
  font-weight: 400;
  font-size: 2.4vw;
  line-height: 3.2vw;

  .left {
    width: 32vw;
    min-width: 150px;
    height: 10vw;
    max-width: 40vw;
    float: left;
    border-radius: 0 5vw 5vw 0;
    background-color: #e8e8e8;

    .left-one {
      width: 95%;
      height: 60%;
      padding: 0.5vw 0.5vw;
      padding-top: 1vw;

      .name {
        float: left;
        margin-right: 1.5vw;
        margin-left: 0.2vw;
      }

      .sex {
        float: left;
      }

      .class {
        float: right;
      }
    }

    .school {
      width: 100%;
      height: 35%;
      padding-left: 15px;
    }
  }

  .right {
    width: 32vw;
    max-width: 40vw;
    height: 10vw;
    background-color: #e8e8e8;
    float: right;
    border-radius: 5vw 0 0 5vw;
    text-align: center;
    position: relative;
    display: flex;
    flex-direction: column;

    .item {
      flex: 1;
      line-height: 5vw;
    }
  }
}

// @media (min-width: 300px) and (min-height: 550px) and (max-width: 600px) and (max-height: 1500px) {
//   .test-box {
//     margin-top: 4px;
//     height: 100vw;
//     position: relative;
//     flex-shrink: 0;
//     margin-bottom: 15px;
//   }

//   .edit-box .not-button {
//     left: 50%;
//     top: 50%;
//     transform: translate(-50%, -50%);
//     width: 20vw;
//     height: 50px;
//     line-height: 29px;
//     border-radius: 50%;
//     font-size: 10px;
//     text-align: center;
//     font-family: Arial;
//   }

//   .edit-box button {
//     cursor: pointer;
//     position: absolute;
//     width: 106px;
//     height: 41px;
//     border-radius: 10px;
//     font-size: 14px;
//     text-align: center;
//   }

//   .vision-result div {
//     width: 12px;
//     height: 12px;
//     margin: 10px 5px;
//   }
// }
</style>
